window.addEventListener("load", function () {
  var that;
  var index = 3;
  class Tab {
    constructor(id) {
      that = this;
      this.mign = document.querySelector(id);
      this.ul = this.mign.querySelector("ul");
      this.add = this.mign.querySelector(".tabadd");
      this.fathersec = this.mign.querySelector(".tabscon");
      this.init();
    }
    // 初始化
    init() {
      this.dy();
      for (var i = 0; i < this.lis.length; i++) {
        this.lis[i].index = i;
        this.lis[i].onclick = this.qh;
        this.del[i].onclick = this.sc;
        this.span[i].ondblclick = this.xg;
        this.sections[i].ondblclick = this.xg;
      }
      this.add.onclick = this.tj;
    }
    // 获取的全部调用元素
    dy() {
      this.lis = this.mign.querySelectorAll("li");
      this.sections = this.mign.querySelectorAll("section");
      this.del = this.mign.querySelectorAll(".icon-guanbi");
      this.span = this.ul.querySelectorAll("li span:nth-child(1)");
      console.log(this.span);
    }
    //切换
    qh() {
      that.qc();
      this.className = "liactive";
      that.sections[this.index].className = "conactive";
    }
    //清除
    qc() {
      for (var i = 0; i < this.lis.length; i++) {
        this.lis[i].className = "";
        this.sections[i].className = "";
      }
    }
    //添加

    tj() {
      that.qc();
      index++;
      var li = `<li class="liactive"><span>测试${index}</span><span class="iconfont icon-guanbi"></span></li>`;
      var sj = Math.random();
      //   function getRandom(min, max) {
      //     return Math.floor(Math.random() * (max - min + 1)) + min;
      //   }
      //   var sj = getRandom(29, 50);
      var section = `<section class="conactive">测试${sj}</section>`;
      that.ul.insertAdjacentHTML("beforeend", li);
      that.fathersec.insertAdjacentHTML("beforeend", section);
      that.init();
    }
    //删除
    sc(e) {
      e //阻止冒泡[DOM推荐标准(ie678不兼容)]
        //ie678用cancelBubble = true
        //兼容处理快捷键jr-zzmp/jr-stopPropagation
        .stopPropagation();
      var index = this.parentNode.index;
      console.log(index);
      that.lis[index].remove();
      that.sections[index].remove();
      that.init();
      if (document.querySelectorAll(".icon-guanbi")) return;
      index--;
      if (index < 0) {
        index = 0;
      }
      that.lis[index] && that.lis[index].click();
    }
    //修改
    xg() {
      var str = this.innerHTML;
      console.log("111");
      this.innerHTML = `<input type="text" value="${str}"/>`;
      // that.innerHTML=`<input type="text" value="${str}"/>`
      var input = this.children[0];
      input.select();
      input.ondblclick = function (e) {
        e.stopPropagation();
      };
      input.onblur = function () {
        this.parentNode.innerHTML = this.value;
        this.parentNode.className='red'
      };
      input.onkeyup = function (e) {
        if (e.keyCode === 13) {
         this.blur()
        }
      };
    }
  }

  new Tab("#tab");
});
